﻿using System;
using System.IO;
using System.Web;
using System.Reflection;

namespace gms.data {
	// Not 100% done, so this will be its only comment. WEEE!!!
	public class PluginManager {
		public static string Path = HttpContext.Current.Request.PhysicalApplicationPath + "plugins";

		public static string[] Plugins {
			get {
				string[] output = Directory.GetFiles(Path, "*.dll");

				for (int i = 0; i < output.Length; i++) {
					output[i] = output[i].Substring(output[i].LastIndexOf("\\") + 1, (output[i].LastIndexOf(".") - output[i].LastIndexOf("\\")) - 1);
				}

				return output;
			}
		}

		public static IGameSystem LoadPlugin(string PluginName) {
			Assembly asmFile = null;
			Type asmType = null;
			IGameSystem retval = null;
			string fqn = Path + "\\" + PluginName;

			if (fqn.IndexOf(".dll") == -1) {
				fqn += ".dll";
			}

			if (File.Exists(fqn)) {
				asmFile = Assembly.LoadFile(fqn);
				asmType = asmFile.GetType(asmFile.GetTypes()[0].FullName);
				retval = (IGameSystem)Activator.CreateInstance(asmType);
			}

			return retval;
		}
	}
}